const xlsx = require("node-xlsx");
const getInvestTree = require("./getInvestTree");
const fs = require("fs");
const sheetTitle = [
  "上级机构名称",
  "法定代表人",
  "控股比例",
  "联系方式",
  "经营状态",
  "企业类型",
  "注册地址",
  "经营范围",
  "行政区划",
  "所属行业",
  "统⼀社会信⽤代码",
];

let xlsxArr = [];

const createXlsxArr = (cname) => [
  {
    name: cname,
    data: [["一级", "二级", "三级", "四级", "五级", "六级"]],
  },
  {
    name: "一级对应字段",
    data: [["一级单位", ...sheetTitle]],
  },
  {
    name: "二级对应字段",
    data: [["二级单位", ...sheetTitle]],
  },
  {
    name: "三级对应字段",
    data: [["三级单位", ...sheetTitle]],
  },
  {
    name: "四级对应字段",
    data: [["四级单位", ...sheetTitle]],
  },
  {
    name: "五级对应字段",
    data: [["五级单位", ...sheetTitle]],
  },
  {
    name: "六级对应字段",
    data: [["六级单位", ...sheetTitle]],
  },
];

/**
 *
 * @param {*} level 数据层级
 * @param {*} data
 * @param {*} parent
 */
const createSingleSheet = (level, data, parent) => {
  const sheet = xlsxArr[level];
  sheet.data.push([
    data.name, // "二级单位",
    parent.length ? parent[parent.length - 1] : "", // "上级机构名称",
    "", // "法定代表人",
    data.percent, // "控股比例",
    "", // "联系方式",
    data.regStatus, // "经营状态",
    data.lable, // "企业类型",
    "", // "注册地址",
    "", // "经营范围",
    "", // "行政区划",
    "", // "所属行业",
    data.creditCode, // "统⼀社会信⽤代码",
  ]);
  // 总表逻辑
  if (data.children.length) {
    data.children.forEach((item) => {
      createSingleSheet(level + 1, item, [...parent, data.name]);
    });
  } else {
    // 总sheet
    xlsxArr[0].data.push([...parent, data.name]);
  }
};

/**
 *
 * @param {*} cname 公司名称
 * @param {*} data 天眼查数据
 */
const getXlsxArr = async (cname) => {
  // const data = await getInvestTree(cname);
  let data =[]
  const files = fs.readdirSync(__dirname + '/jsonFile')
  for (file of files) {
    data=require(`${__dirname}/jsonFile/${file}`).result
  }
  xlsxArr = createXlsxArr(cname);
  data.forEach((item) => {
    createSingleSheet(1, item, []);
  });
  return xlsxArr;
};

/**
 *
 * @param {*} companyName 查询的公司名称
 * @returns
 */
const generateExcel = async(companyName) => {
    const data = await getXlsxArr(companyName);
    return xlsx.build(data);
};

module.exports = generateExcel;
